package main

import (
	"encoding/json"
	"fmt"
	"github.com/patrickmn/go-cache"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"io/ioutil"
	"os"
	"time"
)

func getUserDao(login Login, db *gorm.DB) (User, error) {
	var user User
	if login.IsAdmin {
		sql := "SELECT * FROM users WHERE username = ? AND org_id = ? " +
			"AND username = (SELECT admin_username FROM organs WHERE id = ? LIMIT 1) LIMIT 1;"
		err := db.Raw(sql, login.Username, login.OrgId, login.OrgId).Scan(&user).Error
		return user, err
	} else {
		sql := "SELECT * FROM users WHERE username = ? AND org_id = ? LIMIT 1;"
		err := db.Raw(sql, login.Username, login.OrgId).Scan(&user).Error
		return user, err
	}
}
func getOrganByID(id string, db *gorm.DB) (Organ, error) {
	var org Organ
	er := db.Model(&Organ{}).Where("id = ?", id).First(&org).Error
	return org, er
}
func getAllOrgan(db *gorm.DB) ([]Organ, error) {
	var org []Organ
	er := db.Model(&Organ{}).Select("*").Scan(&org).Error
	return org, er
}
func initDB() (*gorm.DB, *cache.Cache) {
	tokenCache := cache.New(5*time.Minute, 10*time.Minute)
	jsonFile, err := os.Open("config.json")
	if err != nil {
		panic(err)
	}
	// 要记得关闭
	defer func(jsonFile *os.File) {
		err := jsonFile.Close()
		if err != nil {
			panic(err)
		}
	}(jsonFile)
	byteValue, _ := ioutil.ReadAll(jsonFile)
	var config DBConfig
	er := json.Unmarshal(byteValue, &config)
	if er != nil {
		panic(er)
	}
	c := config.Mysql
	dsn := c.Username + ":" + c.Password + "@tcp(" + c.Address + ":" + c.Port + ")/" + c.DBname + "?charset=utf8mb4&parseTime=True&loc=Local"
	fmt.Println(dsn)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	dbPool, err := db.DB()
	if err != nil {
		panic(err)
		return nil, nil
	}
	dbPool.SetMaxIdleConns(10)
	dbPool.SetMaxOpenConns(100)
	dbPool.SetConnMaxLifetime(time.Hour)
	s := SavedVote{}
	err = db.AutoMigrate(&s)
	if err != nil {
		panic(err)
		return nil, nil
	}
	return db, tokenCache
}

func getUserCount(id string, db *gorm.DB) int {
	var res int
	sql := "select count(username) from users where org_id = ?;"
	db.Raw(sql, id).Scan(&res)
	return res
}
func getVoteCount(id string, db *gorm.DB) int {
	var res int
	sql := "select count(name) from saved_votes where org_id = ?;"
	db.Raw(sql, id).Scan(&res)
	return res
}
